package com.dogegg.lbblog.annotation;

import com.dogegg.lbblog.intercept.*;
import com.dogegg.lbblog.support.LogProcessor;
import com.dogegg.lbblog.support.UserDetail;
import com.dogegg.lbblog.support.UserDetailService;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportAware;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

@Configuration
public class ProxyLogConfiguration  implements ImportAware {

    protected AnnotationAttributes enableLog;

    @Bean
    public LogRecordOperationSource logRecordOperationSource(){
        return new AnnotationLogRecordOperationSource();
    }

    @Bean
    public LogRecordInterceptor logRecordInterceptor(LogRecordOperationSource logRecordOperationSource,
                                                     ObjectProvider<UserDetailService> userDetailServiceObjectProvider,
                                                     ObjectProvider<LogProcessor> logProcessorsProvider){

        UserDetailService userService = userDetailServiceObjectProvider.getIfAvailable();
        if(userService == null){
            userService = ()-> new UserDetail() {
                public String getName() {
                    return "default";
                }
            };
        }
        LogRecordInterceptor logRecordInterceptor = new LogRecordInterceptor(logRecordOperationSource,userService);
        if(logProcessorsProvider.getIfAvailable() != null){
            logRecordInterceptor.setProcessor(logProcessorsProvider.getIfAvailable());
        }
        return logRecordInterceptor;
    }

    @Bean
    public BeanFactoryLogOperationSourceAdvisor logAdvisor(
            LogRecordOperationSource logRecordOperationSource,
            LogRecordInterceptor logRecordInterceptor) {
        BeanFactoryLogOperationSourceAdvisor advisor = new BeanFactoryLogOperationSourceAdvisor();
        advisor.setLogRecordOperationSource(logRecordOperationSource);
        advisor.setAdvice(logRecordInterceptor);
        if (this.enableLog != null) {
            advisor.setOrder(this.enableLog.<Integer>getNumber("order"));
        }
        return advisor;
    }


    @Override
    public void setImportMetadata(AnnotationMetadata importMetadata) {
        this.enableLog = AnnotationAttributes.fromMap(
                importMetadata.getAnnotationAttributes(EnableLogRecord.class.getName()));
    }
}
